<script>
import { cloneDeep as deepClone } from '@/utils/methods'
import render from '@/applyComponents/render/render.js'
import { Message } from 'element-ui'

const ruleTrigger = {
    'el-input': 'blur',
    'el-input-number': 'blur',
    'el-select': 'change',
    'el-radio-group': 'change',
    'el-checkbox-group': 'change',
    'el-cascader': 'change',
    'el-time-picker': 'change',
    'el-date-picker': 'change',
    'el-rate': 'change',
}

const layouts = {
    colFormItem(h, scheme) {
        const config = scheme.__config__
        const listeners = buildListeners.call(this, scheme)

        let labelWidth = config.labelWidth ? `${config.labelWidth * scheme.__dpr__}px` : null
        if (config.showLabel === false) labelWidth = '0'
        let className = config.labelBold ? 'label-bold' : ''
        return (
            <el-col span={config.span}>
                <el-form-item
                    class={className}
                    label-width={labelWidth}
                    prop={scheme.__vModel__}
                    required={config.required}
                    label={config.showLabel ? config.label : ''}
                >
                    <render conf={scheme} {...{ on: listeners }} />
                </el-form-item>
            </el-col>
        )
    },
    rowFormItem(h, scheme) {
        let child = renderChildren.apply(this, arguments)
        if (scheme.type === 'flex') {
            child = (
                <el-row type={scheme.type} justify={scheme.justify} align={scheme.align}>
                    {child}
                </el-row>
            )
        }
        return (
            <el-col span={scheme.span}>
                <el-row gutter={scheme.gutter}>{child}</el-row>
            </el-col>
        )
    },
}

function renderFrom(h) {
    const { formConfCopy } = this
    console.log(formConfCopy, '...formConfCopy')
    return (
        <el-row gutter={formConfCopy.gutter}>
            <el-form
                size={formConfCopy.size}
                label-position={formConfCopy.labelPosition}
                disabled={formConfCopy.disabled}
                label-width={`${formConfCopy.labelWidth}px`}
                ref={formConfCopy.formRef} // model不能直接赋值 https://github.com/vuejs/jsx/issues/49#issuecomment-472013664
                props={{ model: this[formConfCopy.formModel] }}
                rules={this[formConfCopy.formRules]}
            >
                {renderFormItem.call(this, h, formConfCopy.fields)}{' '}
                {false && formConfCopy.formBtns && formBtns.call(this, h, formConfCopy.commands)}
            </el-form>
        </el-row>
    )
}

function formBtns(h, commands) {
    // <el-button onClick={this.resetForm}>重置</el-button>
    return (
        <el-col>
            <div class="center">
                {commands.map(item => {
                    return (
                        <el-button className=" pr40 pl40 f16" type="primary" onClick={() => this.submitForm(item)}>
                            {item}
                        </el-button>
                    )
                })}
            </div>
        </el-col>
    )
}

function renderFormItem(h, elementList) {
    const {
        formConfCopy: { disabled },
    } = this
    return elementList.map(scheme => {
        const config = scheme.__config__
        const layout = layouts[config.layout]

        // phone extra 手机端像素比
        scheme.__dpr__ = this.dpr
        scheme.__isMobile__ = this.isMobile
        scheme.__preview__ = this.preview
        scheme.disabled = disabled || scheme.disabled

        if (layout) {
            return layout.call(this, h, scheme)
        }
        throw new Error(`没有与${config.layout}匹配的layout`)
    })
}

function renderChildren(h, scheme) {
    const config = scheme.__config__
    if (!Array.isArray(config.children)) return null
    return renderFormItem.call(this, h, config.children)
}

function setValue(val, config, scheme) {
    this.$set(config, 'defaultValue', val)
    this.$set(this[this.formConf.formModel], scheme.__vModel__, val)
}

function buildListeners(scheme) {
    const config = scheme.__config__
    const methods = this.formConf.__methods__ || {}
    const listeners = {}

    // 给__methods__中的方法绑定this和event
    Object.keys(methods).forEach(key => {
        listeners[key] = val => methods[key].call(this, val)
    })
    // 响应 render.js 中的 vModel $emit('input', val)
    listeners.input = val => setValue.call(this, val, config, scheme)

    return listeners
}

export default {
    components: {
        render,
    },
    props: {
        formConf: {
            type: Object,
            required: true,
        },
        dpr: {
            type: Number,
            default: 1,
        },
        isMobile: {
            type: Boolean,
            default: false,
        },
        preview: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const data = {
            formConfCopy: deepClone(this.formConf),
            [this.formConf.formModel]: {},
            [this.formConf.formRules]: {},
        }
        this.initFormData(data.formConfCopy.fields, data[this.formConf.formModel])
        this.buildRules(data.formConfCopy.fields, data[this.formConf.formRules])
        return data
    },
    methods: {
        initFormData(componentList, formData) {
            componentList.forEach(cur => {
                const config = cur.__config__
                if (cur.__vModel__) formData[cur.__vModel__] = config.defaultValue
                if (config.children) this.initFormData(config.children, formData)
            })
        },
        buildRules(componentList, rules) {
            componentList.forEach(cur => {
                const config = cur.__config__
                if (Array.isArray(config.regList)) {
                    if (config.required) {
                        const required = { required: config.required, message: cur.placeholder }
                        if (Array.isArray(config.defaultValue)) {
                            required.type = 'array'
                            required.message = `请至少选择一个${config.label}`
                        }
                        required.message === undefined && (required.message = `${config.label}不能为空`)
                        config.regList.push(required)
                    }
                    rules[cur.__vModel__] = config.regList.map(item => {
                        item.pattern && (item.pattern = eval(item.pattern))
                        item.trigger = ruleTrigger && ruleTrigger[config.tag]
                        return item
                    })
                }
                if (config.children) this.buildRules(config.children, rules)
            })
        },
        resetForm() {
            this.formConfCopy = deepClone(this.formConf)
            this.$refs[this.formConf.formRef].resetFields()
        },
        submitForm(type) {
            this.$refs[this.formConf.formRef].validate((boolean, object) => {
                if (!boolean) {
                    let arr = Object.keys(object)
                    let message = object[arr[0]][0].message
                    Message.error(message)
                    return false
                }
                // 触发sumit事件
                this.$emit('submit', this[this.formConf.formModel], type)
                return true
            })
        },
    },
    render(h) {
        return renderFrom.call(this, h)
    },
}
</script>
